package com.lfk.justwetools.Component.FlashTextView;

import ohos.agp.components.Component;
import ohos.agp.render.LinearShader;
import ohos.app.Context;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Matrix;
import ohos.agp.render.Paint;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Text;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * Created by liufengkai on 15/11/6.
 */
public class FlashTextView extends Text implements Component.DrawTask, Component.LayoutRefreshedListener {
    private int mViewWidth = 0;
    private Paint mPaint;
    private LinearShader mLinearGradient;
    private Matrix mGradientMatrix;
    private int mTranslate = 0;

    public FlashTextView(Context context) {
        super(context);
        init();
    }

    public FlashTextView(Context context, AttrSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        addDrawTask(this);
        setLayoutRefreshedListener(this);
    }

    @Override
    public void onRefreshed(Component component) {
        if (mViewWidth == 0) {
            mViewWidth = getEstimatedWidth();
            if (mViewWidth > 0) {
//                mPaint = getPaint(); // TODO: NOT SUPPORT IN HOS
//                mLinearGradient = new LinearShader(
//                        new Point[]{new Point(0, 0), new Point(mViewWidth, 0)},
//                        null,
//                        new Color[]{
//                                Color.BLUE,
//                                Color.WHITE,
//                                Color.BLUE
//                        },
//                        Shader.TileMode.CLAMP_TILEMODE);
//                mPaint.setShader(mLinearGradient, Paint.ShaderType.LINEAR_SHADER);
                mGradientMatrix = new Matrix();
            }
        }
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (mGradientMatrix != null) {
            mTranslate += mViewWidth / 5;
            if (mTranslate > 2 * mViewWidth) {
                mTranslate = -mTranslate;
            }
            mGradientMatrix.setTranslate(mTranslate, 0);
//            Log.d("translate" ,mTranslate+"");
            mLinearGradient.setShaderMatrix(mGradientMatrix);
            new EventHandler(EventRunner.getMainEventRunner()).postTask(() -> invalidate(), 100);
        }
    }
}
